<template>
  <view class="main">
    <u-navbar
      title="矿数卫士"
      back-icon-color="#fff"
      title-color="#fff"
      :background="{ backgroundColor: 'rgb(61, 95, 255)' }"
    >
      <view slot="right" class="u-flex">
        <u-image @click="toChart" width="54" height="42" src="/static/image/chart.png" class="u-m-r-10" />
        <!-- <u-image
          @click="$refs.search.showXZ = true"
          width="40"
          height="40"
          src="/static/image/filter.png"
          class="u-m-r-20"
        /> -->

        <u-image @click="goSearch" width="40" height="40" src="/static/image/filter.png" class="u-m-r-20" />
      </view>
    </u-navbar>

    <!-- 区县和煤矿筛选 -->
    <!-- <city-andCustomer
      isCountyName="countyStr"
      isCountyId="countyNo"
      isCustomerName="customerName"
      isCustomerId="customerNo"
      mineUrl="/guard/common/getCustomers"
      countyUrl="/guard/common/getCounties"
      :getSearchData="searchData"
      @searchList="searchList"
    ></city-andCustomer> -->
    <view class="top-header">
      <div class="time-body">
        <view class="flex date">
          <u-button
            v-for="(obj, i) in dateTypeList"
            :key="obj"
            :type="searchData.btType === i ? 'primary' : 'default'"
            class="bt"
            @click.native="monthDay(i)"
            >{{ obj }}</u-button
          >
        </view>
      </div>
      <div class="time-body u-flex">
        <uni-datetime-picker
          type="date"
          :border="false"
          placeholder="请选择开始日期"
          :end="end"
          class="u-m-l-30"
          :clear-icon="false"
          return-type="string"
          v-model="searchData.beginDate"
          @change="changeDate('0')"
        />
        <text class="u-m-l-10 u-m-r-10">至</text>
        <uni-datetime-picker
          type="date"
          :border="false"
          placeholder="请选择结束日期"
          :start="start"
          class="u-m-r-30"
          :clear-icon="false"
          return-type="string"
          v-model="searchData.endDate"
          @change="changeDate('1')"
        />
      </div>
    </view>
    <view class="u-p-20">
      <!-- <view class="title-box u-font-sm">
        <view class="title u-m-b-15">处置概览</view>
      </view>

      <u-grid :col="3" class="content-box" :border="false">
        <u-grid-item>
          <view class="content">
            <view class="u-m-b-10">异常总数</view>
            <view style="color: rgb(61, 95, 255)">{{ cardInfo.appTotalCount }}</view>
          </view>
        </u-grid-item>
        <u-grid-item @click="handleViewDispose('4')">
          <view class="content">
            <view class="u-m-b-10">已闭环异常</view>
            <view class="underline" style="color: rgb(61, 95, 255)">{{ cardInfo.yesDisposalCount }}</view>
          </view>
        </u-grid-item>
        <u-grid-item @click="handleViewDispose('5')">
          <view class="content">
            <view class="u-m-b-10">未闭环异常</view>
            <view class="underline" style="color: rgb(61, 95, 255)">{{ cardInfo.noDisposalCount }}</view>
          </view>
        </u-grid-item>
      </u-grid> -->
      <view v-if="hasUserIsDisposalByApp" class="title-box u-font-sm">
        <view class="title u-m-b-15">我的处置管理（最近30天）</view>
      </view>

      <u-grid v-if="hasUserIsDisposalByApp" :col="3" class="content-box" :border="false">
        <u-grid-item @click="handleViewDispose('1')">
          <view class="content">
            <view class="u-m-b-10">待核查异常</view>
            <view class="underline" style="color: rgb(61, 95, 255)">{{ disposalData.checkCount }}</view>
          </view>
        </u-grid-item>
        <u-grid-item @click="handleViewDispose('2')">
          <view class="content">
            <view class="u-m-b-10">临近超时异常</view>
            <view class="underline" style="color: rgb(61, 95, 255)">{{ disposalData.overtimeCount }}</view>
          </view>
        </u-grid-item>
        <u-grid-item @click="handleViewDispose('3')">
          <view class="content">
            <view class="u-m-b-10">超时未响应异常</view>
            <view class="underline" style="color: rgb(61, 95, 255)">{{ disposalData.overtimeNoCount }}</view>
          </view>
        </u-grid-item>
      </u-grid>
      <u-collapse :accordion="false" ref="collapseView">
        <u-collapse-item :open="true" v-for="(item, index) in cardInfoList" :key="index">
          <template slot="title">
            <view class="title-box list-title u-font-sm">
              <view class="title">{{ item.moduleName }}</view>
              <text class="tiao">共{{ myReduce(item) }}条</text>
            </view>
          </template>

          <u-grid :col="3" class="content-box">
            <u-grid-item v-for="(dataItem, key) in item.functionList" :key="key" class="content">
              <view>
                <view class="u-m-b-10">{{ dataItem.functionName }}</view>
                <view class="underline" @click="goPage(dataItem)">{{ dataItem.anomalousNum }}</view>
              </view>
            </u-grid-item>
          </u-grid>
        </u-collapse-item>

        <u-collapse-item :open="true">
          <template slot="title">
            <view class="title-box list-title u-font-sm">
              <view class="title">企业异常清单</view>
            </view>
          </template>

          <u-table class="mytable" :bg-color="'#fff'">
            <u-tr>
              <u-th>企业名称</u-th>
              <u-th v-for="obj in firmUnusalLabel" :key="obj.props">{{ obj.label }}</u-th>
            </u-tr>
            <u-tr v-for="obj in firmUnusualList" :key="obj.customerNo">
              <u-td>{{ obj.customerName }}</u-td>
              <u-td v-for="it in firmUnusalLabel" class="my-num" :key="it.props">{{ obj[it.props] }}</u-td>
            </u-tr>
          </u-table>
        </u-collapse-item>
      </u-collapse>
    </view>
    <search ref="search" @submitDate="submitDate" />
  </view>
</template>

<script>
import search from "./search.vue";
import cityAndCustomer from "@/pages/components/cityAndCustomer.vue"; // 区县和煤矿企业下拉组件
export default {
  components: { search, cityAndCustomer },
  data() {
    return {
      dateTypeList: ["前一天", "后一天", "当日"],
      searchData: {
        countyNo: "",
        countyStr: "",
        // customerStr: '所有煤矿',
        customerName: "", //企业名称
        customerNo: "", // //企业编码
        beginDate: "",
        endDate: "",
        btType: "",
      },
      xqIp: {
        color: "rgb(61, 95, 255)",
      },
      firmUnusalLabel: [],
      firmUnusualList: [],
      cardInfoList: [],
      cardInfo: {},
      disposalData: {},
      $USER: {},
      funcList: [],
      isQueryType: "",
      hasUserIsDisposalByApp: false,
      emitEvent: "intelligentDetectionIndex",
      start: "",
      end: "",
    };
  },
  onShow() {
    this.getData();
  },
  onLoad() {
    let app = getApp().globalData.userInfo;
    this.$USER = app;
    if (app.countyNo) {
      this.searchData.countyNo = app.countyNo.length <= 4 ? "" : app.countyNo;
    }
    this.initTime();
    this.init();
    uni.$on(this.emitEvent, async (res) => {
      this.searchData = {
        ...res,
        pageNumber: 1,
      };
      this.init();
      this.initTime();
    });
  },
  onReady() {
    // this.getData();
  },
  onUnload() {
    // 清除监听
    uni.$off(this.emitEvent);
  },
  methods: {
    /**
     * 初始时间范围
     */
    initTime() {
      const { beginDate, endDate } = this.searchData;
      if (beginDate && endDate) {
        this.$nextTick(() => {
          this.start = this.$date(this.searchData.beginDate).substring(0, 10);
          this.end = this.$date(this.searchData.endDate).substring(0, 10);
        });
      } else {
        this.$set(this.searchData, "btType", 2);
        const date = this.$u.date();
        this.start = date.substring(0, 10);
        this.end = date.substring(0, 10);
        this.searchData.beginDate = this.start;
        this.searchData.endDate = this.end;
      }
    },
    changeDate() {
      this.$set(this.searchData, "btType", "");
      this.$nextTick(() => {
        this.start = this.$date(this.searchData.beginDate).substring(0, 10);
        this.end = this.$date(this.searchData.endDate).substring(0, 10);
        this.getData();
      });
    },
    async init() {
      await this.getFcList();
    },
    async getHasUserIsDisposalByApp() {
      const { body } = await this.$get("/analyzeReports/judgementUserIsDisposalByApp");
      this.hasUserIsDisposalByApp = body;
    },
    monthDay(val) {
      const date = this.$u.date();
      this.searchData.btType = val;
      if (val === 0) {
        let timestamp =
          this.searchData.beginDate &&
          this.searchData.endDate &&
          new Date(this.$date(this.searchData.endDate).substr(0, 10) + " 00:00:00").getTime() -
            new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime() <
            24 * 60 * 60000
            ? new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime()
            : new Date(date.substr(0, 10) + " 00:00:00").getTime();
        // 前一天
        let prevTime = this.$date(timestamp - 24 * 60 * 60000);
        // 后一天
        let nextTime = this.$date(timestamp - 60000);

        this.searchData.beginDate = prevTime.substring(0, 10);
        this.searchData.endDate = nextTime.substring(0, 10);
      } else if (val === 1) {
        let timestamp =
          this.searchData.beginDate &&
          this.searchData.endDate &&
          new Date(this.$date(this.searchData.endDate).substr(0, 10) + " 00:00:00").getTime() -
            new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime() <
            24 * 60 * 60000
            ? new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 23:59:59").getTime()
            : new Date(date.substr(0, 10) + " 23:59:59").getTime();
        // 前一天
        let prevTime = this.$date(timestamp + 60000);
        // 后一天
        let nextTime = this.$date(timestamp + 24 * 60 * 60000);

        this.searchData.beginDate = prevTime.substring(0, 10);
        this.searchData.endDate = nextTime.substring(0, 10);
      } else if (val === 2) {
        this.searchData.beginDate = date.substring(0, 10);
        this.searchData.endDate = date.substring(0, 10);
      } else if (val === 3) {
        this.searchData.beginDate = this.$timeScopeThisMonth()[0].substring(0, 10);
        this.searchData.endDate = date.substring(0, 10);
      }
      this.$nextTick(() => {
        this.start = this.$date(this.searchData.beginDate).substring(0, 10);
        this.end = this.$date(this.searchData.endDate).substring(0, 10);
      });
      this.getData();
    },
    /**
     * 搜索
     */
    goSearch() {
      const form = {
        ...this.searchData,
      };
      uni.navigateTo({
        url: `./guardScreen?form=${JSON.stringify(form)}&emitEvent=${this.emitEvent}`,
      });
    },
    goPage(obj) {
      const { customerNo, customerStr, beginDate, endDate, countyNo, btType } = this.searchData;
      const params = {
        ...obj,
        beginDate: beginDate,
        endDate: endDate,
        countyNo: countyNo,
        customerNo: customerNo,
        customerStr: customerStr,
        btType: btType,
        // isQueryType: this.isQueryType,
        isQueryType: "",
      };
      //
      let url = "";
      switch (obj.functionCode) {
        case "19":
          url = "./listGrowup";
          break;
        case "06":
          url = "./listGas";
          break;
        default:
          url = "./list";
          break;
      }
      //
      uni.navigateTo({
        url: `${url}?item=${JSON.stringify(params)}`,
      });
    },
    myReduce(arr) {
      let sum = 0;

      arr.functionList.forEach((item) => {
        sum += item.anomalousNum;
      });

      return sum;
    },
    // fReduce(arr) {
    //   let sum = 0;
    //   arr.forEach((ite) => {
    //     ite.functionList.forEach((item) => {
    //       sum += item.anomalousNum;
    //     });
    //   });

    //   return sum;
    // },
    getTotal() {
      const date = [this.$getDateCycleBeginEnd(30, "yyyy-MM-dd")[0], this.$date(new Date(), "yyyy-MM-dd")];
      const params = {
        beginDate: date[0],
        county: this.searchData.countyNo,
        customerNo: this.searchData.customerNo,
        endDate: date[1],
      };
      this.$post("/analyzeReports/main/getAppMainList", params).then((res) => {
        const { body } = res;
        if (body) {
          this.cardInfo = body;
        }
      });
    },
    //获取处置管理数据
    getDisposalCountByHome() {
      const date = [this.$getDateCycleBeginEnd(30, "yyyy-MM-dd")[0], this.$date(new Date(), "yyyy-MM-dd")];
      const params = {
        startTime: date[0],
        customerNo: this.searchData.customerNo,
        countyNo: this.searchData.countyNo,
        endTime: date[1],
      };
      this.$post("/analyzeReports/getDisposalCountByHome", params).then((res) => {
        const { body } = res;
        if (body) {
          this.disposalData = body;
        }
      });
    },
    /**
     * 数据概览切换
     */
    changeData(type) {
      this.isQueryType = type;
      // this.getCardInfoData();
      // this.getFirmUnusualData();
    },
    /**
     * 处置管理页面跳转
     */
    handleViewDispose(type) {
      const date = [this.$getDateCycleBeginEnd(30, "yyyy-MM-dd")[0], this.$date(new Date(), "yyyy-MM-dd")];
      const { customerNo, customerStr, beginDate, endDate, countyNo, btType } = this.searchData;
      const params = {
        beginDate: date[0],
        endDate: date[1],
        countyNo: countyNo,
        customerNo: customerNo,
        customerStr: customerStr,
        // isQueryType: this.isQueryType,
        type: type,
        isQueryType: "",
      };
      uni.navigateTo({
        url: `./disposeList?item=${JSON.stringify(params)}`,
      });
    },
    /**
     * 请求卡片数据
     */
    getCardInfoData() {
      const params = {
        beginDate: this.searchData.beginDate,
        countyNo: this.searchData.countyNo,
        customerNo: this.searchData.customerNo,
        endDate: this.searchData.endDate,
        // isQueryType: this.isQueryType,
        isQueryType: "",
      };
      this.$post("/guard/home/page/getModuleAnomalousCount", params).then((res) => {
        const { body } = res;
        if (Array.isArray(body)) {
          this.cardInfoList = body;
        }
      });
    },
    /**
     * 处理企业异常清单数据
     */
    splitFirmUnusualData(data) {
      const labels = [];
      const tableData = [];

      // 二维数组倒置处理
      if (data.length !== 0) {
        for (let i = 0; i < data[0].customerAnomalousList.length; i++) {
          for (let j = 0; j < data.length; j++) {
            if (!labels[j]) {
              labels[j] = {
                label: data[j].anomalousName,
                props: "anomalousName" + j,
                datas: {
                  type: data[j].anomalousName,
                  functionId: data[j].anomalousId,
                  functionCode: data[j].anomalousCode,
                  functionTableName: data[j].anomalousTableName,
                  typeCode: data[j].typeCode,
                  sensorType: data[j].sensorType,
                  moduleId: data[j].moduleId,
                  moduleName: data[j].moduleName,
                },
              };
            }
            const oldItem = tableData[i] || {};
            // 修改为固定第一项为排序条件
            tableData[i] = {
              ...oldItem,
              customerNo: data[0].customerAnomalousList[i].customerNo,
              customerName: data[0].customerAnomalousList[i].customerName,
              ["anomalousName" + j]: data[j].customerAnomalousList.find(
                (item) => item.customerNo === data[0].customerAnomalousList[i].customerNo
              ).anomalousNum,
            };
          }
        }
      }
      this.firmUnusalLabel = labels;
      this.firmUnusualList = tableData;
      //
      const that = this;
      that.$nextTick(() => {
        uni.showLoading();
        setTimeout(() => {
          that.$refs.collapseView.init();
          uni.hideLoading();
        }, 500);
      });
    },
    getData() {
      this.getHasUserIsDisposalByApp();
      // this.getTotal();
      this.getDisposalCountByHome();
      this.getCardInfoData();
      this.getFirmUnusualData();
    },
    /**
     * 请求企业异常清单数据
     */
    getFirmUnusualData() {
      const params = {
        beginDate: this.searchData.beginDate,
        countyNo: this.searchData.countyNo,
        customerNo: this.searchData.customerNo,
        endDate: this.searchData.endDate,
        // isQueryType: this.isQueryType,
        isQueryType: "",
      };
      const url = "/guard/home/page/getCustomerModuleAnomalousCount";
      this.$post(url, params).then((res) => {
        const { body } = res;
        if (Array.isArray(body)) {
          this.splitFirmUnusualData(body);
        }
      });
    },
    async getFcList() {
      const { body } = await this.$get("/guard/home/page/getFunctionList");
      let arr = [];
      body.forEach((it) => {
        arr.push(it.functionCode);
      });
      this.funcList = arr;
    },
    toChart() {
      const { countyNo, customerNo, beginDate, endDate } = this.searchData;
      const params = {
        countyNo,
        customerNo,
        beginDate,
        endDate,
        functionCodes: this.funcList.join(","),
        isCustom: 0,
      };
      uni.navigateTo({
        url: `./chart?item=${JSON.stringify(params)}`,
      });
    },
    searchList(e) {
      // 获取筛选的区县和煤矿名称
      this.searchData = Object.assign(this.searchData, e);
      this.init();
      this.getData();
    },
  },
};
</script>
<style lang="scss" scoped>
// 背景
page {
  background: #f7f7fa;
}
/deep/.is-click {
  .u-grid-item-box {
    border: 1px solid rgb(61, 95, 255);
  }
}
/deep/ .u-grid-item-box {
  background: white;
  overflow: hidden;
}

.title-box {
  display: flex;
  justify-content: space-between;

  .tl-bt {
    margin: 0;
  }
}

.title {
  border-left: 2px solid rgb(89, 89, 89);
  text-indent: 10px;
}

.search {
  .xq {
    width: 8em;

    .uicon-arrow-down-fill {
      color: rgb(61, 95, 255) !important;
    }
  }

  .mk {
    flex: 1;
    margin-left: 1em;

    .u-input--border {
      border-radius: 22.5px;
    }
  }
}

.content {
  text-align: center;
}

.tiao {
  color: rgb(153, 153, 153);
}

.u-grid-item {
  background: inherit !important;
  padding: 3px;
}

.list-title {
  flex: 1;
}

.underline {
  text-decoration: underline;
  color: rgb(61, 95, 255);
}
.top-header {
  background: #fff;
  padding-bottom: 10px;
  .date {
    margin: 10px 10px;
    /deep/ .u-btn--primary {
      color: #3d5fff;
      border-radius: 4px;
      border: 1px solid rgb(61, 95, 255);
      background: rgba(61, 95, 255, 0.1);
    }
    /deep/ .u-btn--default {
      color: #595959;
      border-radius: 4px;
      border: none;
      background: rgba(153, 153, 153, 0.1);
    }
    /deep/.u-hairline-border {
      &:after {
        border: none;
      }
    }
    /deep/ .u-size-primary {
      height: 30px;
      line-height: 30px;
    }
    /deep/ .u-size-default {
      height: 30px;
      line-height: 30px;
    }
    .bt {
      border-radius: 4px;
      flex: 1;
      margin: 0 5px;
      &:after {
        border-radius: 4px;
      }
    }
  }
}

.time-body {
  position: relative;
  width: 100%;
  /deep/.uni-date-x {
    background: rgba(153, 153, 153, 0.1) !important;
    color: #999999 !important;
    border-radius: 4px !important;
  }
}
.mytable {
  .u-td {
    height: inherit;

    font-size: 0.9em !important;
  }

  .u-td,
  .u-th {
    background: white;
    padding: 10px !important;
  }

  .u-th {
    font-weight: 500;
  }

  .my-num:nth-child(even) {
    color: rgb(255, 159, 64) !important;
  }

  .my-num:nth-child(odd) {
    color: rgb(250, 93, 124) !important;
  }
}
</style>
